document.addEventListener('DOMContentLoaded', function() {
    // 获取DOM元素
    const imageUpload = document.getElementById('image-file');
    const imagePreview = document.querySelector('.image-preview');
    const previewImg = document.getElementById('preview');
    const searchBtn = document.querySelector('.search-btn');
    const resultCards = document.querySelector('.result-cards');
    const fileName = document.querySelector('.file-name');
    const fileSize = document.querySelector('.file-size');
    
    // 后端API地址
    const API_BASE_URL = 'http://81.69.225.207:5003/api';

    // 文件上传处理
    imageUpload.addEventListener('change', function(e) {
        const file = e.target.files[0];
        if (file) {
            if (!file.type.startsWith('image/')) {
                alert('请上传图片文件');
                return;
            }

            const reader = new FileReader();
            reader.onload = function(e) {
                previewImg.src = e.target.result;
                imagePreview.style.display = 'block';
                searchBtn.disabled = false;

                // 显示文件信息
                fileName.textContent = file.name;
                fileSize.textContent = formatFileSize(file.size);
            };
            reader.readAsDataURL(file);
        }
    });

    // 拖拽上传处理
    const dropZone = document.querySelector('.image-upload');
    
    dropZone.addEventListener('dragover', (e) => {
        e.preventDefault();
        dropZone.style.borderColor = '#2c5cff';
        dropZone.style.background = 'rgba(44, 92, 255, 0.05)';
    });

    dropZone.addEventListener('dragleave', () => {
        dropZone.style.borderColor = '#ddd';
        dropZone.style.background = 'none';
    });

    dropZone.addEventListener('drop', (e) => {
        e.preventDefault();
        dropZone.style.borderColor = '#ddd';
        dropZone.style.background = 'none';
        
        const file = e.dataTransfer.files[0];
        if (file && file.type.startsWith('image/')) {
            imageUpload.files = e.dataTransfer.files;
            const reader = new FileReader();
            reader.onload = function(e) {
                previewImg.src = e.target.result;
                imagePreview.style.display = 'block';
                searchBtn.disabled = false;

                fileName.textContent = file.name;
                fileSize.textContent = formatFileSize(file.size);
            };
            reader.readAsDataURL(file);
        } else {
            alert('请上传图片文件');
        }
    });

    // 检索按钮点击事件
    searchBtn.addEventListener('click', async function() {
        try {
            searchBtn.disabled = true;
            searchBtn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> 处理中...';
            
            // 清空之前的结果
            resultCards.innerHTML = `
                <div class="loading-message">
                    <i class="fas fa-spinner fa-spin"></i>
                    <span>正在检索图片，请稍候...</span>
                </div>
            `;
            
            const base64Image = previewImg.src.split(',')[1];
            
            const response = await fetch(`${API_BASE_URL}/image-retrieval/submit`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({
                    image: base64Image
                })
            });

            if (!response.ok) {
                throw new Error('处理请求失败');
            }

            const data = await response.json();
            
            if (data.error) {
                throw new Error(data.error);
            }

            // 添加5秒延时
            await new Promise(resolve => setTimeout(resolve, 5000));
            
            // 清空加载提示
            resultCards.innerHTML = '';
            
            // 显示图片
            if (data.results && data.results.length > 0) {
                const imageGrid = document.createElement('div');
                imageGrid.className = 'image-grid';
                
                data.results.forEach(image => {
                    const imageCard = document.createElement('div');
                    imageCard.className = 'image-card';
                    imageCard.innerHTML = `
                        <img src="${image.url}" alt="上传的图片" onerror="this.src='placeholder.jpg'">
                        <div class="image-actions">
                            <button class="download-btn" onclick="downloadImage('${image.url}', 'downloaded_image')">
                                <i class="fas fa-download"></i> 下载图片
                            </button>
                        </div>
                    `;
                    imageGrid.appendChild(imageCard);
                });
                
                resultCards.appendChild(imageGrid);
            } else {
                resultCards.innerHTML = `
                    <div class="no-results">
                        <i class="fas fa-search"></i>
                        <p>未找到相关图片</p>
                    </div>
                `;
            }

        } catch (error) {
            console.error('处理失败:', error);
            resultCards.innerHTML = `
                <div class="error-message">
                    <i class="fas fa-exclamation-circle"></i>
                    <p>${error.message || '处理失败，请稍后重试'}</p>
                </div>
            `;
        } finally {
            searchBtn.disabled = false;
            searchBtn.innerHTML = '<i class="fas fa-search"></i> 开始检索图片';
        }
    });

    // 格式化文件大小
    function formatFileSize(bytes) {
        if (bytes === 0) return '0 B';
        const k = 1024;
        const sizes = ['B', 'KB', 'MB', 'GB'];
        const i = Math.floor(Math.log(bytes) / Math.log(k));
        return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
    }

    // 添加下载函数（在 DOMContentLoaded 事件处理函数外部）
    function downloadImage(dataUrl, fileName) {
        const link = document.createElement('a');
        link.href = dataUrl;
        link.download = fileName + '.jpg';
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
    }
}); 